<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>账号密码文件上传测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        h1 {
            color: #333;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        
        .upload-area:hover {
            border-color: #007bff;
        }
        
        .upload-area.dragover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        
        .file-info {
            background: #e9ecef;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 10px;
            display: none;
        }
        
        .btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        .btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        
        .btn-success {
            background: #28a745;
        }
        
        .progress {
            height: 20px;
            background: #e9ecef;
            border-radius: 4px;
            margin: 10px 0;
            display: none;
        }
        
        .progress-bar {
            height: 100%;
            background: #007bff;
            border-radius: 4px;
            width: 0%;
            transition: width 0.3s;
        }
        
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            display: none;
        }
        
        .result.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        
        .result.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .credentials-list {
            margin-top: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .credential-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>账号密码文件上传测试</h1>
        
        <div class="upload-area" id="uploadArea">
            <p>点击选择文件或拖拽文件到这里</p>
            <p style="font-size: 12px; color: #666; margin-top: 10px;">
                支持格式: TXT, CSV, Excel, Word, PDF
            </p>
            <input type="file" id="fileInput" style="display: none;" accept=".txt,.csv,.xlsx,.xls,.docx,.pdf">
        </div>
        
        <div class="file-info" id="fileInfo"></div>
        
        <div class="progress" id="progress">
            <div class="progress-bar" id="progressBar"></div>
        </div>
        
        <button class="btn" id="uploadBtn" disabled>上传并解析</button>
        <button class="btn btn-success" id="saveBtn" style="display: none;">保存到数据库</button>
        
        <div class="result" id="result"></div>
    </div>

    <script>
        class FileUploadTest {
            constructor() {
                this.uploadArea = document.getElementById('uploadArea');
                this.fileInput = document.getElementById('fileInput');
                this.fileInfo = document.getElementById('fileInfo');
                this.uploadBtn = document.getElementById('uploadBtn');
                this.saveBtn = document.getElementById('saveBtn');
                this.progress = document.getElementById('progress');
                this.progressBar = document.getElementById('progressBar');
                this.result = document.getElementById('result');
                
                this.currentFile = null;
                this.parseResult = null;
                
                this.initEventListeners();
            }
            
            initEventListeners() {
                // 点击上传区域
                this.uploadArea.addEventListener('click', () => {
                    this.fileInput.click();
                });
                
                // 文件选择变化
                this.fileInput.addEventListener('change', (e) => {
                    if (e.target.files.length > 0) {
                        this.handleFileSelect(e.target.files[0]);
                    }
                });
                
                // 拖拽功能
                this.uploadArea.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    this.uploadArea.classList.add('dragover');
                });
                
                this.uploadArea.addEventListener('dragleave', () => {
                    this.uploadArea.classList.remove('dragover');
                });
                
                this.uploadArea.addEventListener('drop', (e) => {
                    e.preventDefault();
                    this.uploadArea.classList.remove('dragover');
                    if (e.dataTransfer.files.length > 0) {
                        this.handleFileSelect(e.dataTransfer.files[0]);
                    }
                });
                
                // 上传按钮
                this.uploadBtn.addEventListener('click', () => {
                    this.uploadFile();
                });
                
                // 保存按钮
                this.saveBtn.addEventListener('click', () => {
                    this.saveCredentials();
                });
            }
            
            handleFileSelect(file) {
                this.currentFile = file;
                this.fileInfo.innerHTML = `
                    <strong>已选择文件:</strong> ${file.name}<br>
                    <strong>文件大小:</strong> ${this.formatFileSize(file.size)}<br>
                    <strong>文件类型:</strong> ${file.type || '未知'}
                `;
                this.fileInfo.style.display = 'block';
                this.uploadBtn.disabled = false;
                this.hideResult();
            }
            
            async uploadFile() {
                if (!this.currentFile) return;
                
                this.uploadBtn.disabled = true;
                this.showProgress();
                
                const formData = new FormData();
                formData.append('file', this.currentFile);
                
                try {
                    // 模拟上传进度
                    this.simulateProgress();
                    
                    // 发送到后端API
                    const response = await fetch('/api/deepseek/chat/', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    this.hideProgress();
                    
                    if (result.success) {
                        this.parseResult = result;
                        this.showSuccess(`文件解析成功！共发现 ${result.parse_result.credentials?.length || 0} 条记录`);
                        this.showCredentials(result.parse_result.credentials);
                        this.saveBtn.style.display = 'inline-block';
                    } else {
                        this.showError(`解析失败: ${result.error}`);
                    }
                    
                } catch (error) {
                    this.hideProgress();
                    this.showError(`上传失败: ${error.message}`);
                } finally {
                    this.uploadBtn.disabled = false;
                }
            }
            
            async saveCredentials() {
                if (!this.parseResult) return;
                
                try {
                    this.saveBtn.disabled = true;
                    this.saveBtn.textContent = '保存中...';
                    
                    const response = await fetch('/api/credentials/save/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            credentials: this.parseResult.parse_result.credentials,
                            file_info: this.parseResult.file_info
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        this.showSuccess(`保存成功！共保存 ${result.saved_count} 条记录到数据库`);
                        this.saveBtn.style.display = 'none';
                    } else {
                        this.showError(`保存失败: ${result.error}`);
                    }
                    
                } catch (error) {
                    this.showError(`保存失败: ${error.message}`);
                } finally {
                    this.saveBtn.disabled = false;
                    this.saveBtn.textContent = '保存到数据库';
                }
            }
            
            simulateProgress() {
                let progress = 0;
                const interval = setInterval(() => {
                    progress += 5;
                    this.updateProgress(progress);
                    
                    if (progress >= 90) {
                        clearInterval(interval);
                    }
                }, 100);
            }
            
            showProgress() {
                this.progress.style.display = 'block';
                this.updateProgress(0);
            }
            
            hideProgress() {
                this.updateProgress(100);
                setTimeout(() => {
                    this.progress.style.display = 'none';
                }, 500);
            }
            
            updateProgress(percent) {
                this.progressBar.style.width = percent + '%';
            }
            
            showSuccess(message) {
                this.result.className = 'result success';
                this.result.innerHTML = `<strong>成功:</strong> ${message}`;
                this.result.style.display = 'block';
            }
            
            showError(message) {
                this.result.className = 'result error';
                this.result.innerHTML = `<strong>错误:</strong> ${message}`;
                this.result.style.display = 'block';
            }
            
            hideResult() {
                this.result.style.display = 'none';
            }
            
            showCredentials(credentials) {
                if (!credentials || credentials.length === 0) return;
                
                const credentialsHtml = credentials.map((cred, index) => `
                    <div class="credential-item">
                        <strong>记录 ${index + 1}:</strong><br>
                        位置: ${cred.location || '未知'}<br>
                        设备: ${cred.device_name || '未知'}<br>
                        用户: ${cred.username || '未知'}<br>
                        密码: ${cred.password ? '***' : '未知'}<br>
                        状态: ${cred.status || '未知'}<br>
                        备注: ${cred.notes || '无'}
                    </div>
                `).join('');
                
                this.result.innerHTML += `
                    <div class="credentials-list">
                        <h4>解析结果:</h4>
                        ${credentialsHtml}
                    </div>
                `;
            }
            
            formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            new FileUploadTest();
        });
    </script>
</body>
</html>